package yongxin.controller.processreport;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.chromate.ChromateEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.chromate.ChromateServiceI;
import yongxin.service.matchinegroup.MatchinegroupServiceI;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.tasks.TasksServiceI;
import yongxin.service.workshop.WorkshopServiceI;

/**   
 * @Title: Controller
 * @Description: 工序汇报
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/processReport11Controller")
public class ProcessReportP11Controller extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ProcessReportP11Controller.class);

	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ChromateServiceI chromateService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private WorkshopServiceI workshopService;
	
	@Autowired
	private TasksServiceI tasksService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "processReport")
	public ModelAndView processReport(HttpServletRequest request) {
		String process=request.getParameter("process");
		request.setAttribute("process", process);
		
		return new ModelAndView("yongxin/process/processReportList_p11");
		
		
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		String process=request.getParameter("process");
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		//查询条件组装器
		cq.eq("cprocess", process);
		if(StringUtil.isEmpty(processReport.getFstate())){
		cq.in("fstate", new Object[]{"0","1"});
		}
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if (user.getUserName().contains("bxg"))
		{
			cq.like("fbcph", "S%");
			
		} else if (user.getUserName().contains("tg"))
		{
			cq.like("fbcph", "Y%");
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
		//String total_trzl = String.valueOf(processService.findOneForJdbc("select sum(CONVERT(numeric(19,2),ftrzl)) sum_trzl from t_processreport where cprocess = 'p11' and fstate in('0','1')").get("sum_trzl"));
		//total_trzl = total_trzl == "null"?"":total_trzl;
		//dataGrid.setFooter("fbcph:投入总计 ,fworkshop:" + total_trzl + ",ftrkd:合计,ftrzl,fcczl,fbfzl");
		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		
		TagUtil.datagrid(response, dataGrid);
		
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}

		
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();
        
		String fwlname = request.getParameter("fwlname");
		// 分卷信息
		String ftrhds = request.getParameter("ftrhds");
		String ftrkds = request.getParameter("ftrkds");
		String ftrzls = request.getParameter("ftrzls");

		String[] ffjhs = request.getParameterValues("ffjhs");
		String[] fcds = request.getParameterValues("fcds");
		String[] ffqzls = request.getParameterValues("ffqzls");
		String[] fnotes = request.getParameterValues("fnotes");
		String[] fnprocess = request.getParameterValues("fnprocess");

		if (ffjhs != null && ffjhs.length >= 1)        // 分卷
		{
			if (StringUtil.isNotEmpty(processReport.getFstate()))
			{

				if (2 > 1)    // 存在分卷
				{
					// 保存之前先删除（ freportId 为其母卷id ）
					String sql = " delete from t_chromate where freportId = ? ";
					int row = systemService.executeSql(sql, processReport.getId());

					for (int i = 0; i < ffjhs.length; i++)
					{

						try
						{

							// 保存镀铬记录
							ChromateEntity product = new ChromateEntity();
							product.setFbcph(processReport.getFbcph());
							product.setFtrkd(ftrkds);
							product.setFtrhd(ftrhds);
							product.setFtrzl(ftrzls);
							product.setFfjh(ffjhs[i]);
							product.setFcd(fcds[i]);
							product.setFfqzl(ffqzls[i]);
							product.setNprocess(fnprocess[i]);
							product.setFnote(fnotes[i]);
							product.setFreportId(processReport.getId());    // 关联母卷id

							systemService.save(product);

							if (processReport.getFstate().equals("2") && fnprocess[i] != null && !fnprocess[i].equals("over"))   // 未入库的作汇报
							{
								ProcessReportEntity cprocessReport = new ProcessReportEntity();
								cprocessReport.setFwlname(fwlname);
								cprocessReport.setCprocess(processReport.getCprocess());
								cprocessReport.setFbcph(ffjhs[i]);
								cprocessReport.setFtrhd(ftrhds);
								cprocessReport.setFtrkd(ftrkds);
								cprocessReport.setFtrzl(ffqzls[i]);
								cprocessReport.setNprocess(fnprocess[i]);
								cprocessReport.setFisleft("1"); // 标记为 镀铬 分卷未入库的
								cprocessReport.setFstate("6");
								

								if (!fnprocess[i].equals(processReport.getCprocess()))
								{
									ProcessEntity entity2 = new ProcessEntity();
									entity2.setFreportid(cprocessReport.getId());
									entity2.setFbcph(ffjhs[i]);
									entity2.setFprocess(processReport.getCprocess());
									processService.save(entity2);
								}
								// 保存下一道工序记录（即母卷分切后剩余的卷信息）
								ProcessReportEntity nprocessReport = new ProcessReportEntity();
								nprocessReport.setFwlname(fwlname);
								nprocessReport.setCprocess(fnprocess[i]);
								nprocessReport.setFbcph(ffjhs[i]);
								nprocessReport.setFtrhd(ftrhds);
								nprocessReport.setFtrkd(ftrkds);
								nprocessReport.setFtrzl(ffqzls[i]);
								nprocessReport.setFisleft("1"); // 标记为镀铬分卷 未入库的
																// 作用是方便查看工序流转图时不显示母卷信息
								nprocessReport.setFstate("0");
								processReportService.save(nprocessReport);
 
								cprocessReport.setfNextReportId(nprocessReport.getId());
								processReportService.save(cprocessReport);
								
								ProcessEntity entity = new ProcessEntity();
								entity.setFreportid(nprocessReport.getId());
								entity.setFbcph(ffjhs[i]);
								entity.setFprocess(fnprocess[i]);
								processService.save(entity);
							}

						} catch (Exception e)
						{
							e.printStackTrace();
							message = "工序汇报失败";
						}
					}
				}

				try
				{

					message = "工序汇报成功";

					if (processReport.getFstate().equals("1")) // 保存操作
					{
						ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
						MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
						t.setFstate("1");
						processReportService.saveOrUpdate(t);

					} else if (processReport.getFstate().equals("2")) // 汇报操作
					{
						ProcessEntity entity = new ProcessEntity();
						entity.setFbcph(processReport.getFbcph());
						entity.setFprocess(processReport.getNprocess());
						processService.save(entity);

						ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
                        
						if(!processReport.getNprocess().equals("over")){
						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setFwlname(fwlname);
						nprocessReport.setCprocess(processReport.getNprocess());
						nprocessReport.setFbcph(processReport.getFbcph());
						nprocessReport.setFtrhd(processReport.getFtrhd());
						nprocessReport.setFtrkd(processReport.getFtrkd());
						nprocessReport.setFtrzl(processReport.getFcczl());
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);
                        
						t.setfNextReportId(nprocessReport.getId());   //  母卷跟 剩余卷
						
						entity.setFreportid(nprocessReport.getId());
						processService.saveOrUpdate(entity);
						}
						
						
						MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
						t.setFstate("2");
						t.setNprocess(processReport.getNprocess());
						processReportService.saveOrUpdate(t);
					}
				} catch (Exception e)
				{
					e.printStackTrace();
					message = "工序汇报失败";
				}

			}
		}else if(ffjhs == null )        //  整卷流下去
		{
			try
			{

				message = "工序汇报成功";
				
				if (processReport.getFstate().equals("1")) // 保存操作
				{
					// 保存之前先删除（ freportId 为其母卷id ）
					String sql = " delete from t_chromate where freportId = ? ";
					int row = systemService.executeSql(sql, processReport.getId());
					
					ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
					MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
					t.setFstate("1");
					processReportService.saveOrUpdate(t);

				} else if (processReport.getFstate().equals("2")) // 汇报操作
				{
					// 保存之前先删除（ freportId 为其母卷id ）
					String sql = " delete from t_chromate where freportId = ? ";
					int row = systemService.executeSql(sql, processReport.getId());
					
					ProcessEntity entity = new ProcessEntity();
					entity.setFbcph(processReport.getFbcph());
					entity.setFprocess(processReport.getNprocess());
					processService.save(entity);

					ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
                    
					if(!processReport.getNprocess().equals("over")){
					ProcessReportEntity nprocessReport = new ProcessReportEntity();
					nprocessReport.setFwlname(fwlname);
					nprocessReport.setCprocess(processReport.getNprocess());
					nprocessReport.setFbcph(processReport.getFbcph());
					nprocessReport.setFtrhd(processReport.getFtrhd());
					nprocessReport.setFtrkd(processReport.getFtrkd());
					nprocessReport.setFtrzl(processReport.getFcczl());
					nprocessReport.setFstate("0");
					processReportService.save(nprocessReport);
                    
					t.setfNextReportId(nprocessReport.getId());   
					
					entity.setFreportid(nprocessReport.getId());
					processService.saveOrUpdate(entity);
					}
					
					
					MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
					t.setFstate("2");
					t.setNprocess(processReport.getNprocess());
					processReportService.saveOrUpdate(t);
				}
			} catch (Exception e)
			{
				e.printStackTrace();
				message = "工序汇报失败";
			}
			
		}

		j.setMsg(message);
		return j;
	}
	
	
	
	 /*
     * 
     * 反汇报
     * 
     */
	@RequestMapping(params = "returnReport")
	@ResponseBody
	public AjaxJson returnReport(ProcessReportEntity processReport, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();
		message = "反汇报成功";

		// 得到工序的id 、本场批号、下一工序 、下一工序id
		String id = request.getParameter("id");
		String fbcph = request.getParameter("fbcph");
		String fnprocess = request.getParameter("fnprocess");
		String fNextReportId = request.getParameter("fNextReportId");

		ProcessReportEntity p = systemService.getEntity(ProcessReportEntity.class, id);

		String sql = " delete from t_processreport where fbcph like ? and create_date > ? ";
		String sql2 = " delete from t_process where fbcph like ? and create_date > ?  ";
		String sql3 = " delete from t_chromate where fbcph like ? and create_date > ?  ";

		try
		{
			// 删除之后汇报的记录
			systemService.executeSql(sql, fbcph + '%', p.getCreateDate());
			systemService.executeSql(sql2, fbcph + '%', p.getCreateDate());
			systemService.executeSql(sql3, fbcph + '%', p.getCreateDate());

			// 增加一条工序记录
			ProcessEntity entity = new ProcessEntity();
			entity.setFreportid(p.getId());
			entity.setFbcph(processReport.getFbcph());
			entity.setFprocess("p11");
			processService.save(entity);

			// 修改本道工序状态
			p.setFstate("1");
			processReportService.saveOrUpdate(p);
			

		} catch (Exception e)
		{
			e.printStackTrace();
			message = "反汇报失败";
		}

		j.setMsg(message);
		return j;
	}
	
	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ProcessReportEntity processReport, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(processReport.getId())) {
			processReport = processReportService.getEntity(ProcessReportEntity.class, processReport.getId());

			if (processReport.getFstate().equals("2"))       // 查看  已完工  信息
			{

				String hql = " from ChromateEntity where 1 = 1 and fbcph = ? and freportId = ?";
				List<ChromateEntity> list = chromateService.findHql(hql, processReport.getFbcph(), processReport.getId());
				List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
				
				String ftrzls = "";
				if(list.size() > 0)
				{
					
				   ftrzls = list.get(0).getFtrzl();
				}
				req.setAttribute("ftrzls", ftrzls);
				
				
				req.setAttribute("workshopList", workshopList);

				req.setAttribute("processReportPage", processReport);
				req.setAttribute("productList", list);
				return new ModelAndView("yongxin/process/processReport_p11_2");
			} else
			{

				//String hql = " from ChromateEntity where 1 = 1 and fbcph = ? ";
				//List<ChromateEntity> list = chromateService.findHql(hql, processReport.getFbcph());
				String sql = " select COUNT(fbcph) count1 from t_cut where fbcph = ? ";
				String sql2 = " select COUNT(fbcph) count2 from t_chromate where fbcph =  ? ";
				int a =  (Integer) systemService.findOneForJdbc(sql, processReport.getFbcph()).get("count1");
				int b =  (Integer) systemService.findOneForJdbc(sql2, processReport.getFbcph()).get("count2");
				int len = a + b;
				
				String hql2 = " from ChromateEntity where 1 = 1 and fbcph = ? and freportId = ?";
				List<ChromateEntity> list2 = chromateService.findHql(hql2, processReport.getFbcph(), processReport.getId());
				String ftrzls = "";
				if(list2.size() > 0)
				{
				   ftrzls = list2.get(0).getFtrzl();
				}
				req.setAttribute("ftrzls", ftrzls);
				
				
				
				List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
				req.setAttribute("workshopList", workshopList);
				req.setAttribute("processReportPage", processReport);
				//req.setAttribute("productList", list);
				req.setAttribute("len", len);
				req.setAttribute("productList2", list2);
				return new ModelAndView("yongxin/process/processReport_p11");

			}
		}
		return new ModelAndView("yongxin/process/processReport_p11");
	}
	
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		String id=request.getParameter("id");
		if (StringUtil.isEmpty(id)) {
			id="nprocess";
		}
		String ofbcph="";
		if(fbcph.indexOf("-")>0){
			ofbcph=fbcph.substring(0,fbcph.indexOf("-"));
		}
		Object[] object=new Object[3];
		object[0]=ofbcph;
		object[1]=fbcph;
		object[2]=fbcph;
		
		String sql=" select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " +
				"   from t_process tp  " +
				"   left join (select tst.typecode,tst.typename " +
				"    from t_s_type tst,t_s_typegroup tstg  " +
				"    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " +
				"     on tp.fprocess=dic.typecode      " +
				"      where tp.fbcph=? and create_date< ( " +
				"		select min(create_date) from t_process t1 where t1.fbcph=? " +
				"      ) " +
				" union " +
				"   select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " +
				"   from t_process tp  " +
				"   left join (select tst.typecode,tst.typename " +
				"    from t_s_type tst,t_s_typegroup tstg  " +
				"    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " +
				"     on tp.fprocess=dic.typecode     " +
				"  where tp.fbcph=?    order by tp.create_date ";
		
		String sql2="select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 +=" where tst.typegroupid=tstg.ID ";
		sql2 +=" and tstg.typegroupcode='ccgx' and tst.typecode!='p1'";
		
		List<Map<String,Object>> maplist=null;
		List<Map<String,Object>> maplist2=null;
		 try{
			 maplist=systemService.findForJdbc(sql, object);
			 maplist2=systemService.findForJdbc(sql2,null);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(maplist);
		 j.setMsg(createSelecte(maplist2,id));
		 
		return j;
	}
	
	private String createSelecte(List<Map<String,Object>> maplist,String id){
		String select="<select id='nprocess' name='"+id+"' class='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist) {
			select +="<option value="+map.get("typecode")+">"+map.get("typename")+"</option>";
		}
		//select = select.replaceAll(select.substring(67,98), "");
		return select;
	}
	
	
	
}
